package chen.web.antispam;

import java.awt.image.BufferedImage;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import chen.web.cache.CacheUtils;

import com.google.code.kaptcha.Producer;

/**
 * 基于uuid的验证码储存器
 * @author chen
 *
 */
public class CaptchaStore {

	private static final String CaptchaTextStoreName = "captcha-text-store";
	public static enum VerifyResult{success, failed, expired};
	
	private Cache captchaTextStore = null;
	
	private Producer captchaProducer;
	public CaptchaStore(Producer captchaProducer){
		this.captchaProducer = captchaProducer;
		captchaTextStore = CacheManager.getInstance().getCache(CaptchaTextStoreName);
		CacheUtils.storeDescription(captchaTextStore, "用于缓存验证码");
	}
	
	/**
	 * 判断验证码是否匹配, 执行此方法后, 验证码总是会失效
	 * @param uuid
	 * @param captcha
	 * @return
	 */
	public VerifyResult verify(String uuid, String captcha){
		VerifyResult result = preVerify(uuid, captcha);
		captchaTextStore.remove(uuid);
		return result;
	}
	
	/**
	 * 判断验证码是否匹配, 执行此方法后, 若验证码不匹配则失效, 匹配则不会失效
	 * @param uuid
	 * @param captcha
	 * @return
	 */
	public VerifyResult preVerify(String uuid, String captcha){
		Element element = captchaTextStore.get(uuid);
		if(element == null)
			return VerifyResult.expired;
		String storedCaptcha = (String)element.getObjectValue();
		if(storedCaptcha.equalsIgnoreCase(captcha)){
			return VerifyResult.success;
		}
		captchaTextStore.remove(uuid);
		return VerifyResult.failed;
	}
	
	public BufferedImage generateCaptcha(String uuid){
		String capText = captchaProducer.createText();
		BufferedImage bi = captchaProducer.createImage(capText);
		Element element = new Element(uuid, capText);
		captchaTextStore.put(element);
		return bi;
	}
}
